<?php

declare(strict_types=1);

namespace App\Api\Service;

use App\Constants\OrderPayStatus;
use App\Exception\DefaultException;
use App\Model\Order;
use App\Model\Staff;
use Carbon\Carbon;
use Hyperf\Contract\LengthAwarePaginatorInterface;
use Throwable;

class StaffService
{
    private const SCENE = 'staff';

    /**
     * 登录
     * @param array $params
     * @return array
     */
    public function login(array $params): array
    {
        try {
            // 查询员工
            $staff = Staff::query()
                ->where('phone', $params['phone'])
                ->firstOr(['id', 'password'], function () {
                    throw new DefaultException('手机号或密码输入错误');
                });
            if (!password_verify($params['password'], $staff->password)) {
                throw new DefaultException('手机号或密码输入错误');
            }

            // 生成Token
            $token = user(self::SCENE)->getToken([
                'id' => $staff->id,
            ]);

            return [
                'token' => $token,
            ];
        } catch (DefaultException $e) {
            throw $e;
        } catch (Throwable $e) {
            throw new DefaultException('登录失败，请稍后重试');
        }
    }

    /**
     * 获取员工信息
     * @return Staff
     */
    public function personal(): Staff
    {
        // 查询员工
        $staff = Staff::query()
            ->where('id', api_member_id(self::SCENE))
            ->firstOrFail();

        return $staff->setVisible(['avatar', 'name', 'phone']);
    }

    /**
     * 更新员工信息
     * @param array $params
     * @return void
     */
    public function updatePersonal(array $params): void
    {
        // 员工
        $staff = Staff::query()
            ->where('id', api_member_id(self::SCENE))
            ->firstOrFail();

        // 更新
        $staff->fill($params)->save();
    }

    /**
     * 订单列表
     * @return LengthAwarePaginatorInterface
     */
    public function orderIndex(): LengthAwarePaginatorInterface
    {
        // 参数
        $isDelivery = (int)request()->input('is_delivery');

        // 查询
        $res = Order::query()
            ->with(['orderLessee:order_id,name,phone', 'orderCar:order_id,name,describe'])
            ->where('staff_id', api_member_id(self::SCENE))
            ->where('is_delivery', $isDelivery)
            ->where('pay_status', OrderPayStatus::SUCCESS)
            ->oldest('start_at')
            ->latest('id')
            ->paginate();

        // 周
        $weeks = ['日', '一', '二', '三', '四', '五', '六'];

        // 组装数据
        /** @var Order $model */
        foreach ($res as $model) {
            $model->date = $model->created_at->format('Y.m.d H:i');
            $model->start_date = sprintf($model->start_at->format('Y年m月d日 周%\s H:i'), $weeks[$model->start_at->format('w')]);
            $model->orderLessee->setHidden(['order_id']);
            $model->orderCar->setHidden(['order_id']);
            $model->setVisible(['id', 'date', 'start_date', 'city', 'address', 'orderLessee', 'orderCar', 'is_delivery']);
        }

        return $res;
    }

    /**
     * 订单详情
     * @param mixed $id
     * @return Order
     */
    public function orderShow(mixed $id): Order
    {
        // 查询订单
        $model = Order::query()
            ->with(['orderCar:order_id,name,describe,cover', 'orderLessee:order_id,name,phone,id_card', 'orderInsurance:order_id,level,name,car_damage,car_damage_sub,tripartite,passenger'])
            ->where('id', $id)
            ->where('staff_id', api_member_id(self::SCENE))
            ->where('pay_status', OrderPayStatus::SUCCESS)
            ->firstOrFail();

        // 组装数据
        $model->start_date = $model->start_at->format('Y年m月d日 H:i');
        $model->end_date = $model->end_at->format('Y年m月d日 H:i');
        $model->date = $model->created_at->format('Y.m.d H:i');
        $model->pay_date = $model->getRawOriginal('pay_confirm_at') ? $model->pay_confirm_at->format('Y.m.d H:i') : '';
        $model->orderCar->setHidden(['order_id']);
        $model->orderLessee->setHidden(['order_id']);
        $model->orderInsurance->setHidden(['order_id']);
        $model->setVisible(['orderCar', 'city', 'address', 'start_date', 'end_date', 'day', 'orderLessee', 'orderInsurance', 'no', 'date', 'pay_date', 'is_delivery']);

        return $model;
    }

    /**
     * 确认送达
     * @param mixed $id
     * @return void
     */
    public function updateOrderDelivery(mixed $id): void
    {
        // 查询
        $order = Order::query()
            ->where('id', $id)
            ->where('staff_id', api_member_id(self::SCENE))
            ->where('is_delivery', Order::DISABLE)
            ->where('pay_status', OrderPayStatus::SUCCESS)
            ->firstOrFail();

        // 更新
        $order->is_delivery = Order::ENABLE;
        $order->delivery_at = Carbon::now();
        $order->save();
    }
}
